#include "emotioncontroller.h"
#include "networkcontroller.h"
#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDateTime>

EmotionController::EmotionController(QObject *parent)
    : QObject(parent)
    , m_networkController(nullptr)
    , m_currentEmotion(Neutral)
    , m_currentIntensity(50)
    , m_brightness(80)
    , m_leftEyeConnected(false)
    , m_rightEyeConnected(false)
    , m_connectionCheckTimer(new QTimer(this))
{
    initializeEmotions();
    
    // 初始化网络控制器
    m_networkController = new NetworkController(this);
    
    // 连接网络控制器信号
    connect(m_networkController, &NetworkController::deviceStatusChanged,
            this, &EmotionController::onDeviceStatusChanged);
    
    // 设置连接检查定时器
    m_connectionCheckTimer->setInterval(CONNECTION_CHECK_INTERVAL);
    connect(m_connectionCheckTimer, &QTimer::timeout, this, &EmotionController::checkDeviceConnections);
    m_connectionCheckTimer->start();
    
    // 初始连接检查
    QTimer::singleShot(2000, this, &EmotionController::checkDeviceConnections);
    
    qDebug() << "表情控制器初始化完成 - 简化指令模式";
}

EmotionController::~EmotionController()
{
    if (m_connectionCheckTimer) {
        m_connectionCheckTimer->stop();
    }
}

void EmotionController::initializeEmotions()
{
    // 初始化表情指令映射
    m_emotionCommands[Neutral] = {"NEUTRAL", "中性", 50, false};
    m_emotionCommands[Happy] = {"HAPPY", "开心", 70, true};
    m_emotionCommands[Sad] = {"SAD", "伤心", 60, true};
    m_emotionCommands[Angry] = {"ANGRY", "愤怒", 80, true};
    m_emotionCommands[Surprised] = {"SURPRISED", "惊讶", 75, true};
    m_emotionCommands[Fear] = {"FEAR", "恐惧", 65, true};
    m_emotionCommands[Sleep] = {"SLEEP", "休眠", 10, false};
    
    // 字符串名称映射
    m_emotionNames["neutral"] = Neutral;
    m_emotionNames["happy"] = Happy;
    m_emotionNames["sad"] = Sad;
    m_emotionNames["angry"] = Angry;
    m_emotionNames["surprised"] = Surprised;
    m_emotionNames["fear"] = Fear;
    m_emotionNames["sleep"] = Sleep;
    
    qDebug() << "表情指令映射初始化完成，共" << m_emotionCommands.size() << "种表情";
}

void EmotionController::setEmotion(const QString &emotion, int intensity)
{
    QString lowerEmotion = emotion.toLower();
    if (m_emotionNames.contains(lowerEmotion)) {
        setEmotion(m_emotionNames[lowerEmotion], intensity);
    } else {
        qWarning() << "未知表情类型:" << emotion;
    }
}

void EmotionController::setEmotion(EmotionType emotion, int intensity)
{
    if (!m_emotionCommands.contains(emotion)) {
        qWarning() << "表情类型不存在:" << emotion;
        return;
    }
    
    m_currentEmotion = emotion;
    m_currentIntensity = qBound(0, intensity, 100);
    
    sendEmotionCommand(emotion, m_currentIntensity);
    
    const EmotionCommand &cmd = m_emotionCommands[emotion];
    qDebug() << "设置表情:" << cmd.displayName << "强度:" << m_currentIntensity;
    
    emit emotionChanged(cmd.displayName, m_currentIntensity);
}

void EmotionController::setSleepMode()
{
    qDebug() << "进入休眠模式";
    setEmotion(Sleep, 10);
}

void EmotionController::testDeviceConnection()
{
    qDebug() << "开始测试设备连接...";
    
    // 发送测试指令
    sendSimpleCommand("TEST", LEFT_EYE_INDEX);
    sendSimpleCommand("TEST", RIGHT_EYE_INDEX);
    
    // 延迟检查结果
    QTimer::singleShot(1000, this, &EmotionController::onConnectionTestResult);
}

void EmotionController::setIntensity(int intensity)
{
    setEmotion(m_currentEmotion, intensity);
}

void EmotionController::setBrightness(int brightness)
{
    m_brightness = qBound(0, brightness, 100);
    
    // 发送亮度设置指令
    QJsonObject brightnessCmd;
    brightnessCmd["type"] = "config";
    brightnessCmd["action"] = "set_brightness";
    brightnessCmd["brightness"] = m_brightness;
    brightnessCmd["timestamp"] = QDateTime::currentMSecsSinceEpoch();
    
    if (m_networkController) {
        QJsonDocument doc(brightnessCmd);
        QByteArray data = doc.toJson(QJsonDocument::Compact);
        m_networkController->sendToDisplay(LEFT_EYE_INDEX, data);
        m_networkController->sendToDisplay(RIGHT_EYE_INDEX, data);
    }
    
    qDebug() << "设置亮度:" << m_brightness;
}

bool EmotionController::isLeftEyeConnected() const
{
    return m_leftEyeConnected;
}

bool EmotionController::isRightEyeConnected() const
{
    return m_rightEyeConnected;
}

QString EmotionController::getConnectionStatus() const
{
    if (m_leftEyeConnected && m_rightEyeConnected) {
        return "双眼连接正常";
    } else if (m_leftEyeConnected || m_rightEyeConnected) {
        return QString("%1连接正常")
               .arg(m_leftEyeConnected ? "左眼" : "右眼");
    } else {
        return "设备未连接";
    }
}

void EmotionController::sendEmotionCommand(EmotionType emotion, int intensity)
{
    if (!m_emotionCommands.contains(emotion)) {
        return;
    }
    
    const EmotionCommand &cmd = m_emotionCommands[emotion];
    
    // 创建简化的表情指令
    QJsonObject emotionCmd;
    emotionCmd["type"] = "emotion";
    emotionCmd["action"] = "set";
    emotionCmd["emotion"] = cmd.command;           // 表情标识符
    emotionCmd["intensity"] = intensity;          // 强度 0-100
    emotionCmd["brightness"] = m_brightness;      // 亮度 0-100
    emotionCmd["timestamp"] = QDateTime::currentMSecsSinceEpoch();
    
    if (m_networkController) {
        QJsonDocument doc(emotionCmd);
        QByteArray data = doc.toJson(QJsonDocument::Compact);
        
        // 同时发送给两个设备
        m_networkController->sendToDisplay(LEFT_EYE_INDEX, data);
        m_networkController->sendToDisplay(RIGHT_EYE_INDEX, data);
        
        qDebug() << "发送表情指令:" << cmd.command << "强度:" << intensity;
    }
}

void EmotionController::sendSimpleCommand(const QString &command, int deviceIndex)
{
    QJsonObject simpleCmd;
    simpleCmd["type"] = "command";
    simpleCmd["action"] = command;
    simpleCmd["timestamp"] = QDateTime::currentMSecsSinceEpoch();
    
    if (m_networkController) {
        QJsonDocument doc(simpleCmd);
        QByteArray data = doc.toJson(QJsonDocument::Compact);
        
        if (deviceIndex == -1) {
            // 发送给所有设备
            m_networkController->sendToDisplay(LEFT_EYE_INDEX, data);
            m_networkController->sendToDisplay(RIGHT_EYE_INDEX, data);
        } else {
            // 发送给指定设备
            m_networkController->sendToDisplay(deviceIndex, data);
        }
        
        qDebug() << "发送简单指令:" << command << "设备:" << deviceIndex;
    }
}

void EmotionController::checkDeviceConnections()
{
    if (m_networkController) {
        // 触发设备状态检查
        m_networkController->checkDeviceStatus();
    }
}

void EmotionController::updateConnectionStatus()
{
    bool leftConnected = m_networkController ? m_networkController->isDeviceOnline(LEFT_EYE_INDEX) : false;
    bool rightConnected = m_networkController ? m_networkController->isDeviceOnline(RIGHT_EYE_INDEX) : false;
    
    bool statusChanged = (leftConnected != m_leftEyeConnected) || (rightConnected != m_rightEyeConnected);
    
    m_leftEyeConnected = leftConnected;
    m_rightEyeConnected = rightConnected;
    
    if (statusChanged) {
        qDebug() << "设备连接状态更新 - 左眼:" << (m_leftEyeConnected ? "连接" : "断开") 
                 << "右眼:" << (m_rightEyeConnected ? "连接" : "断开");
        emit connectionStatusChanged(m_leftEyeConnected, m_rightEyeConnected);
    }
}

void EmotionController::onDeviceStatusChanged(int deviceIndex, bool online)
{
    qDebug() << "设备状态变化 - 索引:" << deviceIndex << "状态:" << (online ? "在线" : "离线");
    
    if (deviceIndex == LEFT_EYE_INDEX) {
        m_leftEyeConnected = online;
    } else if (deviceIndex == RIGHT_EYE_INDEX) {
        m_rightEyeConnected = online;
    }
    
    emit connectionStatusChanged(m_leftEyeConnected, m_rightEyeConnected);
}

void EmotionController::onConnectionTestResult()
{
    // 检查测试结果
    updateConnectionStatus();
    
    qDebug() << "连接测试完成:" << getConnectionStatus();
    
    // 发送测试结果信号
    emit deviceTestResult(LEFT_EYE_INDEX, m_leftEyeConnected);
    emit deviceTestResult(RIGHT_EYE_INDEX, m_rightEyeConnected);
} 